<?php
namespace app\admin\controller;
use app\admin\model\Action_prize;

/**
 * 奖品管理
 * Class Member
 */
class PrizeController extends BaseController {

    protected function _initialize() {
        parent::_initialize();
    }

    /**
     * 奖品管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '', $ziduan = 'id', $param='add_time', $sort='desc') {
        $map = [];
		$order = $param. ' '.$sort;
		$this->assign('param', $param);
		$this->assign('sort', $sort);
        if ($keyword) {
            $map[$ziduan] = $keyword;
        }
		$this->assign('ziduan', $ziduan);
        $prize_list = db('action_prize')->where($map)->order($order)->paginate(15, false, get_query());
        return $this->fetch('index', ['prize_list' => $prize_list, 'keyword' => $keyword]);
    }
	
    /**
     * 添加奖品
     * @return mixed
     */
    public function add() {
    	$ks_list = db('action_item')->select();
		$this->assign('ks_list', $ks_list);
        return $this->fetch();
    }

    /**
     * 保存奖品
     */
    public function save() {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
			$data['add_time'] = now_time();
			$data['demand'] = implode(',',$data['demand']);
			$prize_model = new Action_prize();
            if ($prize_model->allowField(true)->save($data)) {
                $this->success('添加成功',url("index"));
            } else {
                $this->error('添加失败');
            }
        }
    }

    /**
     * 编辑奖品
     * @param $id
     * @return mixed
     */
    public function edit($id) {
    	$prize_model = new Action_prize();
        $prize = $prize_model->where('id',$id)->find();
		$prize['demand'] = explode(",",$prize['demand']); 

		$ks_list = db('action_item')->select();
		$this->assign('ks_list', $ks_list);
        return $this->fetch('edit', ['action' => $prize]);
    }

    /**
     * 更新奖品
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
            $data            = $this->request->post();			
			$data['demand'] = implode(',',$data['demand']);
			$prize_model = new Action_prize();
            if ($prize_model->allowField(true)->save($data,['id'=>$id]) !== false) {
                $this->success('更新成功',url("index"));
            } else {
                $this->error('更新失败');
            }
        }
    }
	
	//删除奖品
	public function delete_item(){
		$res = db('action_prize')->where('id',input("id"))->delete();
		if($res){
			 $this->success('删除成功',url("index"));
		}else{
			 $this->success('删除失败');
		}
	}

}
